package com.devilvan.betrice.bilibili.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.devilvan.betrice.bilibili.dto.BilibiliVideoDto;
import com.devilvan.betrice.bilibili.po.BilibiliVideoPo;
import com.devilvan.betrice.bilibili.service.BilibiliVideoService;
import com.devilvan.betrice.bilibili.mapper.BilibiliVideoMapper;
import com.devilvan.betrice.bilibili.repository.BilibiliVideoRepository;
import com.devilvan.betrice.common.BetriceResultCode;
import com.devilvan.betrice.common.BetriceResultVo;
import com.devilvan.betrice.util.UCopy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * @author Evad.Wu
 * @Description Bilibili-视频信息表 业务逻辑类
 * @date 2022-12-22
 */
@Service
public class BilibiliVideoServiceImpl extends ServiceImpl<BilibiliVideoMapper, BilibiliVideoPo> implements BilibiliVideoService {
    @Resource(name = "bilibiliVideoRepository")
    private BilibiliVideoRepository bilibiliVideoRepository;

    @Override
    public BetriceResultVo<BilibiliVideoPo> doBilibiliVideoRequest(BilibiliVideoDto bilibiliVideoDto) {
        BetriceResultVo<BilibiliVideoPo> betriceResultVo = new BetriceResultVo<>();
        try {
            BilibiliVideoPo bilibiliVideoPo = this.findOneByAid(bilibiliVideoDto.getAid());
            if (Optional.ofNullable(bilibiliVideoPo).isPresent()) {
                UCopy.halfCopy(bilibiliVideoDto, bilibiliVideoPo);
                this.updateById(bilibiliVideoPo);
            } else {
                bilibiliVideoPo = this.saveUpdate(bilibiliVideoDto);
            }
            betriceResultVo.result(BetriceResultCode.SUCCESS_200, "操作成功！", bilibiliVideoPo);
        } catch (Exception e) {
            e.printStackTrace();
            betriceResultVo.result(BetriceResultCode.FAILED_500, "操作失败！");
        }
        return betriceResultVo;
    }

    /**
     * 根据aid查询视频信息
     *
     * @param aid 视频ID
     * @return 结果集
     */
    private BilibiliVideoPo findOneByAid(Long aid) {
        LambdaQueryWrapper<BilibiliVideoPo> queryWrapper = new QueryWrapper<BilibiliVideoPo>().lambda();
        queryWrapper.eq(BilibiliVideoPo::getAid, aid);
        return this.getOne(queryWrapper);
    }

    @Override
    public BilibiliVideoPo saveUpdate(BilibiliVideoDto bilibiliVideoDto) {
        BilibiliVideoPo bilibiliVideoPo = new BilibiliVideoPo();
        UCopy.fullCopy(bilibiliVideoDto, bilibiliVideoPo);
        return bilibiliVideoRepository.saveAndFlush(bilibiliVideoPo);
    }

    @Override
    public List<BilibiliVideoPo> saveUpdateBatch(List<BilibiliVideoDto> list) {
        List<BilibiliVideoPo> bilibiliVideoPoList = UCopy.fullCopyCollections(list, BilibiliVideoPo.class);
        return bilibiliVideoRepository.saveAllAndFlush(bilibiliVideoPoList);
    }
}
